package handler

import (
	"CampusRecruitment/pkg/apps"
	"CampusRecruitment/pkg/apps/ctx"
	"CampusRecruitment/pkg/types"
	"CampusRecruitment/pkg/types/errors"
	"bytes"
	"github.com/gin-gonic/gin"
	"mime"
	"net/http"
	"os"
	"path"
)

// IconFileUpload 图标上传
// @Tags 文件
// @Summary 图标上传
// @Accept */*
// @Produce */*
// @Param icon formData file true "图标"
// @router /icons [POST]
// @Success 200
func IconFileUpload(c *gin.Context) {
	ac := ctx.New(c)
	file, err := c.FormFile("icon")
	if err != nil {
		ac.Response(nil, err)
	} else {
		ac.Response(apps.IconFileUpload(file))
	}
}

// FileUpload 简历上传
// @Tags 文件
// @Summary 简历上传
// @Accept */*
// @Produce */*
// @Security AuthToken
// @Param cv formData file true "简历"
// @router /cv [POST]
// @Success 200
func FileUpload(c *gin.Context) {
	ac := ctx.New(c)
	file, err := c.FormFile("cv")
	if err != nil {
		ac.Response(nil, err)
	} else {
		ac.Response(apps.FileUpload(ac, file))
	}
}

// GetCVFile 简历下载
// @Tags 文件
// @Summary 简历下载
// @Accept json
// @Produce json
// @Security AuthToken
// @Param form query types.CVForm true "parameter"
// @router /cv/getFile [GET]
// @Success 200
func GetCVFile(c *gin.Context) {
	ac := ctx.New(c)
	cvFileForm := types.CVForm{}
	if err := ac.Bind(&cvFileForm); err != nil {
		return
	}
	filePath := "uploads/" + cvFileForm.Path
	fileTmp, _ := os.Open(filePath)
	//fileTmp, errByOpenFile := os.Open(filePath)
	defer fileTmp.Close()
	//获取文件的名称
	fileName := path.Base(filePath)
	//if common.IsEmpty(filePath) || common.IsEmpty(fileName) || errByOpenFile != nil {
	//	ac.Logger().Error("获取文件失败")
	//	c.Redirect(http.StatusFound, "/404")
	//	return
	//}
	//强制浏览器下载
	c.Header("Content-Disposition", "attachment; filename="+fileName)
	//浏览器下载或预览
	c.Header("Content-Disposition", "inline;filename="+fileName)
	c.Header("Content-Transfer-Encoding", "utf8")
	c.Header("Cache-Control", "no-cache")

	c.File(filePath)
	return
}

// ReadIconFile 图标下载
// @Tags 文件
// @Summary 图标下载
// @Accept json
// @Produce json
// @Param form query types.IconForm true "parameter"
// @router /icons [GET]
// @Success 200
func ReadIconFile(c *gin.Context) {
	ac := ctx.New(c)
	iconForm := types.IconForm{}
	err := ac.Bind(&iconForm)
	if err != nil {
		return
	}

	buffer := bytes.NewBuffer(nil)
	err = apps.ReadIconFile(ac, buffer, iconForm.Path)
	if err != nil {
		c.String(http.StatusInternalServerError, errors.AutoErrCode(err).Error())
	}
	data := buffer.Bytes()

	contentType := mime.TypeByExtension(path.Ext(iconForm.Path))
	if contentType == "" {
		contentType = http.DetectContentType(data)
	}

	c.Header("Content-Type", contentType)
	_, _ = c.Writer.Write(data)
}
